﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ControlCenter.通讯;
using System.Diagnostics;

namespace 转发程序
{
    /// <summary>
    /// 转发目标
    /// </summary>
    public class TransmitTarget : 转发目标
    {



        #region 转发目标 成员

        public string 目标IP
        {
            get;
            set;
        }

        public int 目标端口
        {

            get;
            set;
        }


        private TcpServerSocket _目标机通讯Socket;

        /// <summary>
        ///  加入Receive事件 然后通过 接收器通讯Socket发出
        /// </summary>
        public TcpServerSocket 目标机通讯Socket
        {
            get { return _目标机通讯Socket; }
            set
            {
                _目标机通讯Socket = value;


            }
        }





        private TcpServerSocket _接收器通讯Socket;
        /// <summary>
        /// 
        /// </summary>
        public TcpServerSocket 接收器通讯Socket
        {
            get { return _接收器通讯Socket; }
            set
            {
                _接收器通讯Socket = value;


            }
        }


        public 转换器 转换器
        {

            get;
            set;
        }



        /// <summary>
        /// 启动转发目标接收数据功能 
        /// 接收后将回发到 接收服务器中
        /// </summary>
        public void 启动转发目标接收数据功能()
        {
            if (目标机通讯Socket != null)
            {
                //使用线程池 接收数据操作
                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((o) =>
                {
# if aa
                    #region 同步接收数据
                    try
                    {
                        while (true)
                        {
                            byte[] buffer = new byte[目标机通讯Socket.Buffer.Length];

                            //接收数据
                            int ReceiveLen = 目标机通讯Socket.Socket.Receive(buffer);

                            //发送到终端设备
                            if (_接收器通讯Socket.Socket.Connected)
                            {
                                _接收器通讯Socket.Socket.Send(buffer.Take(ReceiveLen).ToArray());
                            }
                        }
                    }
                    //远程主机强迫关闭了一个现有联接 异常不做处理
                    catch (System.Net.Sockets.SocketException)
                    {


                    }
                    catch (ObjectDisposedException)
                    {
                    }
                    catch (Exception)
                    {

                        try
                        {
                            目标机通讯Socket.Socket.Close();
                            目标机通讯Socket.Socket.Dispose();
                        }
                        catch
                        {

                        }

                    }
                    #endregion      
#endif
                    #region 异步接收数据,在联接超过20个的时候接收数据会出现大量超过30秒的延迟
                    try
                    {
                        目标机通讯Socket.Socket.BeginReceive(目标机通讯Socket.Buffer, 0, 目标机通讯Socket.Buffer.Length, System.Net.Sockets.SocketFlags.None, AsyncCallback, 目标机通讯Socket);
                    }
                    //远程主机强迫关闭了一个现有联接 异常不做处理
                    catch (System.Net.Sockets.SocketException)
                    {


                    }
                    catch (ObjectDisposedException)
                    {
                    }
                    catch (Exception)
                    {

                        try
                        {

                            目标机通讯Socket.Socket.Close();
                            目标机通讯Socket.Socket.Dispose();
                        }
                        catch
                        {

                        }

                    }
                #endregion


                }));
                    #endregion
                    
            }
        }

        void AsyncCallback(IAsyncResult ar)
        {
            ///是不是成功接收数据
            ///默认没有成功接收数据
            bool receiveed = false;
            //当前的Socket对像
            TcpServerSocket sokcket = (ar.AsyncState as TcpServerSocket);
            //默认缓冲区为 30K
            byte[] buffer = new byte[1024 * 30];
            if (ar.IsCompleted)
            {
                #region 接收数据并发送数据及异常断开的异常处理
                try
                {
                    if (sokcket.Socket.Connected)
                    {
                        //返回收到的字节数
                        int ReceiveLen = sokcket.Socket.EndReceive(ar);
                        //接收数据成功
                        receiveed = true;
                        //发送到终端设备
                        if (_接收器通讯Socket.Socket.Connected)
                        {
                            _接收器通讯Socket.Socket.Send(转换器.ConvertBack(sokcket.Buffer.Take(ReceiveLen).ToArray()));
                            //完成端口发送数据
                            //var buff = sokcket.Buffer.Take(ReceiveLen).ToArray();

                            //_接收器通讯Socket.Socket.BeginSend(buff, 0, buff.Length, System.Net.Sockets.SocketFlags.None, new AsyncCallback((ar1) =>
                            //{
                            //    try
                            //    {
                            //        _接收器通讯Socket.Socket.EndSend(ar1);
                            //    }
                            //    catch (Exception ex)
                            //    {
                            //        var d = ex;
                            //    }
                            //}), _接收器通讯Socket.Socket);
                        }

                        //接着接收异步Socket数据
                        sokcket.Socket.BeginReceive(sokcket.Buffer, 0, sokcket.Buffer.Length, System.Net.Sockets.SocketFlags.None, AsyncCallback, 目标机通讯Socket);
                        
                    }
                }
                catch (Exception oex)
                {
                    receiveed = false;
                    // Debug.WriteLine(string.Format("异常:{0}", oex.Message));
                }

                // 发生错误或客户端断开连接则关闭套接字
                if (!receiveed)
                {
                    try
                    {
                        if (sokcket.Socket.Connected)
                        {
                            sokcket.Socket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                            sokcket.Socket.Close();
                            sokcket.Socket.Dispose();
                        }
                    }
                    catch (Exception oex)
                    {
                        // Debug.WriteLine(string.Format("异常:{0}", oex.Message));
                    }
                }
                #endregion


            }
        }

  




    }
}
